package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class AccountTeamController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def accountTeamList = AccountTeam.findAll("from AccountTeam where user.username = '${username}'", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = AccountTeam.executeQuery("select count(id) from AccountTeam where user.username = '${username}'")

        respond accountTeamList, model: [accountTeamCount: count[0]]

    }

    def show(AccountTeam accountTeam)
    {
        respond accountTeam
    }

    def create()
    {
        def account = Account.findById(params['account'])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (account?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userList = User.list()
            def accountTeams = AccountTeam.findAllByAccount(account)
            accountTeams?.each {
                userList -= it?.user
            }
            respond new AccountTeam(params), model: [userList: userList]
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "account", action: "show", params: [id: account.id])
            return
        }
    }

    @Transactional
    def save(AccountTeam accountTeam)
    {
        if (accountTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (accountTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond accountTeam.errors, view: 'create'
            return
        }

        accountTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'accountTeam.label', default: 'AccountTeam'), accountTeam.id])
                // redirect accountTeam
                redirect(controller: "account", action: "show", params: [id: accountTeam?.account?.id])
            }
            '*' { respond accountTeam, [status: CREATED] }
        }
    }

    def edit(AccountTeam accountTeam)
    {
        respond accountTeam
    }

    @Transactional
    def update(AccountTeam accountTeam)
    {
        if (accountTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (accountTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond accountTeam.errors, view: 'edit'
            return
        }

        accountTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'accountTeam.label', default: 'AccountTeam'), accountTeam.id])
                // redirect accountTeam
                redirect(controller: "account", action: "show", params: [id: accountTeam?.account?.id])
            }
            '*' { respond accountTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(AccountTeam accountTeam)
    {

        if (accountTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        accountTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'accountTeam.label', default: 'AccountTeam'), accountTeam.id])
                // redirect action: "index", method: "GET"
                redirect(controller: "account", action: "show", params: [id: accountTeam?.account?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'accountTeam.label', default: 'AccountTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    // @Transactional
    def searchAccountTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def name = params["name"]
        String sql = "from AccountTeam as u where 1=1 and u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.account.name like '%${name}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and u.account.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(u.id) " + sql

        sql += ' order by createdDate desc'

        def list = AccountTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = AccountTeam.executeQuery(countSql)

        respond list, model: [accountTeamCount: count[0], params: params], view: 'index'
    }

    def exportAccountTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def name = params["name"]
        String sql = "from AccountTeam as u where 1=1 and u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.account.name like '%${name}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and u.account.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(u.id) " + sql

        sql += ' order by createdDate desc'

        def list = AccountTeam.findAll(sql)
        def count = AccountTeam.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=accountTeam.${params.extension}")
            List fields = ["account.account.name", "account.alias", "account.type.name", "account.level.name", "account.industry.name", "account.numberOfEmployees", "account.website", "account.registeredCapital", "account.parent.name", "account.territory.name", "account.user.fullName", "account.description", "account.active", "account.createdDate", "account.modifiedDate"]
            Map labels = ["account.name": "客户名称", "account.alias": "曾用名", "account.type.name": "类型", "account.level.name": "分级", "account.industry.name": "行业", "account.numberOfEmployees": "雇员数量", "account.website": "网站", "account.registeredCapital": "注册资本", "account.parent.name": "上级客户", "account.territory.name": "销售区域", "account.user.fullName": "所有者", "account.description": "描述", "account.active": "启用", "account.createdDate": "创建时间", "account.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
